package cn.slahser.utils;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Hashtable;
import java.util.Vector;

import cn.slahser.serverEntity.Message;
import cn.slahser.serverEntity.ShuoExt;

/***
 * 登入登出tcp连接相关
 * 
 * @author Slahser
 * 
 */
public class LoginClientTCP extends Thread {

	private static ObjectInputStream oin = null;
	private static ObjectOutputStream oout = null;

	private static void conn() throws Exception {
		// 传递通道
		Socket socket = new Socket(SlahserMetaData.IP,
				SlahserMetaData.SERVEPORT);
		oout = new ObjectOutputStream(socket.getOutputStream());
		oin = new ObjectInputStream(socket.getInputStream());
	}

	public static String login(String userid, String password) throws Exception {
		// 连接
		conn();
		// 附带信息
		Message msg = new Message();
		Hashtable<String, Object> table = new Hashtable<String, Object>();
		table.put("userid", userid);
		table.put("password", password);
		msg.setType(Message.LOGIN);
		msg.setValue(table);
		// 写出
		oout.writeObject(msg);
		oout.flush();
		// 返回信息处理
		Message m2 = (Message) oin.readObject();
		// 全局变量一枚
		SlahserMetaData.userid = userid;
		String message = (m2.getReturnValue().get("message").toString());
		if (!message.equalsIgnoreCase("ok")) {
			try {
				oout.close();
				oin.close();
			} catch (Exception e) {
			}
			// 成功的话
		} else {
			// 开启接收服务器
			new AcionClientTCP().start();
		}
		return message;
	}

	/***
	 * 得到数据
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Vector<ShuoExt> getData() {
		// 设置传递信息
		Message msg = new Message();
		msg.setType(Message.DL_DATA);

		synchronized (LoginClientTCP.class) {
			try {
				// 通过流传递信息
				oout.writeObject(msg);
				oout.flush();
				msg = (Message) oin.readObject();
				// 返回信息的处理
				if (msg.getReturnValue().get("message").toString()
						.equalsIgnoreCase("ok")) {
					return (Vector<ShuoExt>) msg.getReturnValue().get("infos");
				}
			} catch (Exception e) {
			}
		}
		return null;
	}

	/***
	 * 发送消息，开辟单独线程
	 * 
	 * @param msg
	 */
	public static void sendMessage(final Message msg) {
		new Thread() {
			public void run() {
				synchronized (LoginClientTCP.class) {
					try {
						oout.writeObject(msg);
						oout.flush();
						oin.readObject();
					} catch (Exception e) {
					}
				}
			};
		}.start();
	}

	public static void close() {
		final Message msg = new Message();
		msg.setType(Message.LOGOUT);
		new Thread() {
			public void run() {
				synchronized (LoginClientTCP.class) {
					try {
						oout.writeObject(msg);
						oout.flush();
						oin.readObject();
						oout.close();
						oin.close();
					} catch (Exception e) {
					}
				}
			};
		}.start();
	}
}
